<?php
class Advego_Buy
{
	private $_user;
	private $_pass;
	private $_host;

	private $_selenium;

	private $_defaultTimeOut = 30000;

	/**
	 * @return the $_user
	 */
	public function getUser()
	{
		return $this->_user;
	}

	/**
	 * @return the $_pass
	 */
	public function getPass()
	{
		return $this->_pass;
	}

	/**
	 * @param field_type $_user
	 */
	public function setUser( $user )
	{
		$this->_user = $user;
	}

	/**
	 * @param field_type $_pass
	 */
	public function setPass( $pass )
	{
		$this->_pass = $pass;
	}

	public function __construct( $host, $user, $pass )
	{
		$this->_user = $user;
		$this->_pass = $pass;
		$this->_host = $host;

		$this->_selenium = new Testing_Selenium( "*iexplore", $host );
		$this->_selenium->start();
		$this->_selenium->setTimeout( 600000 );
	}

	/**
	 *
	 * Покупка статьи по url
	 * @param string $url
	 * @param bool $test покупка без подтверждения
	 * @return number <ul>Возвращаемые значения:<li>-1 - если уже куплена<li> 1 - куплена без подтвержедения<li> 2 - куплена</ul>
	 */
	public function buy( $url, $test = false )
	{
		$message = sprintf( 'Buy item by url - %s', $url );
		Zend_Registry::get( 'logger' )->debug( $message );

		if ( !$this->isLogin() )
		{
			$this->login();
		}

		$this->openAndWait( $url );

		$result = 0;
		if ( $this->isSold() )
		{
			$this->isSold();

			$result = -1;
		}
		else
		{
			$locator = "//a[@onclick='return shop_buy(this);']";
			$this->clickAndWait( $locator );

			$pattern = 'Подвердите покупку статьи';
			$script = sprintf( "selenium.isTextPresent('%s')", $pattern );
			$this->_selenium->waitForCondition( $script, $this->_defaultTimeOut );

			if ( $this->isTextPresent( $pattern ) )
			{
				$result = 1;
			}
		}
		$this->_selenium->close();
		return $result;
	}

	public function grab( $url )
	{
		if ( !$this->isLogin() )
		{
			$this->login();
		}

		$this->openAndWait( $url );

		$selenium = $this->_selenium;
		$title = $selenium->getText( '//h5/a' );

		$desc = '';
		$fullDesc = '';
		if ( $this->isTextPresent( 'Описание' ) && $this->isTextPresent( 'Полный текст статьи' ) )
		{
			$desc = $selenium->getText( "//div[@class='job_desc']" );
			$fullDesc = $selenium->getText( "//div[@class='job_desc'][2]" );
		}
		else if ( $this->isTextPresent( 'Полный текст статьи' ) )
		{
			$fullDesc = $selenium->getText( "//div[@class='job_desc']" );
		}

		$result = array();
		$result[ 'link' ] = $url;
		$result[ 'title' ] = $title;
		$result[ 'desc' ] = $desc;
		$result[ 'fullDesc' ] = $fullDesc;
		return $result;
	}

	public function isSold( $url = '' )
	{
		if ( !empty( $url ) )
		{
			$this->openAndWait( $url );
		}

		$text = 'Статья продана';
		$result = false;
		if ( $this->_selenium->isTextPresent( $text ) )
		{
			$result = true;
		}
		return $result;
	}

	public function login()
	{
		$url = $this->_host . '/login';
		$this->openAndWait( $url );

		$this->_selenium->type( "login", $this->getUser() );
		$this->_selenium->type( "pwd", $this->getPass() );
		$locator = 'id=login_submit';
		$this->clickAndWait( $locator );
	}

	public function logout()
	{
		$locator = "link=Выход";
		$this->clickAndWait( $locator );
	}

	public function isLogin()
	{
		$result = false;
		// если браузер уже залогинен (например, режим "запомнить меня")
		if ( $this->isTextPresent( 'Привет, dansokolov' ) && $this->isTextPresent( 'Мой профиль' ) )
		{
			$result = true;
		}
		return $result;
	}

	public function isTextPresent( $pattern )
	{
		$result = false;
		if ( $this->_selenium->isTextPresent( $pattern ) )
		{
			$result = true;
		}
		return $result;
	}

	public function clickAndWait( $locator, $timeout = 30000 )
	{
		$this->_selenium->click( $locator );
		$this->waitForPageToLoad();
	}

	public function waitForPageToLoad( $timeout = 30000 )
	{
		$this->_selenium->waitForPageToLoad( $timeout );
	}

	public function __destruct()
	{
		$this->stop();
		unset( $this->_selenium );
	}

	private function openAndWait( $url )
	{
		$this->_selenium->open( $url );
		$this->waitForPageToLoad();
	}

	private function stop()
	{
		$this->_selenium->stop();
	}
}